import { BusinessException } from '@/common/exceptions/business.filter';
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';

@Injectable()
export class ToolsService {
  // 通用新增方法
  async _addEntity(repository: Repository<any>, body: any) {
    try {
      const res = await repository.save(body);
      if (!res) {
        throw new BusinessException('error');
      }
      return 'success';
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  // 通用修改方法
  async _updateEntity(repository: Repository<any>, body: any) {
    try {
      const res = await repository.update(body.id, body);
      if (!res) {
        throw new BusinessException('error');
      }
      return 'success';
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  // 通用删除方法
  async _deleteEntity(repository: Repository<any>, id: string) {
    try {
      const res = await repository.delete(id);
      if (!res) {
        throw new BusinessException('error');
      }
      return 'success';
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  // 通用查询方法
  async _findEntity(repository: Repository<any>) {
    try {
      const res = await repository.find();
      if (!res) {
        throw new BusinessException('error');
      }
      return res;
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
}
